package com.zjw.project.oauth;


import com.zjw.entity.po.User;
import com.zjw.entity.po.WeiUsers;
import com.zjw.project.weixin.main.MenuManager;
import com.zjw.project.weixin.util.WeixinUtil;
import com.zjw.service.UserService;
import com.zjw.service.WeiUsersService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Controller
@Slf4j
@RequestMapping("weixinMenu")
public class WeixinMenuOauth {

    @Autowired
    private WeiUsersService weiUsersService;

    @Autowired
    private UserService userService;

    // weixinMenu/oauth
    @RequestMapping("oauth")
    public void oauth(HttpServletResponse response) throws IOException {
        //用户是否同意授权
        String path=MenuManager.REAL_URL+"weixinMenu/oauth/invoke";
        try {
            path=  URLEncoder.encode(path,"UTF-8");
            //https%3A%2F%2Fpassport.baidu.com%2Fphoenix%2Faccount%2Fafterauth%
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String url="https://open.weixin.qq.com/connect/oauth2/authorize" +
                "?appid=" + MenuManager.appId+
                "&redirect_uri=" +path+
                "&response_type=code" +
                "&scope=snsapi_base" +
                "&state=java2005" +
                "#wechat_redirect";
        response.sendRedirect(url);
    }

    @RequestMapping("oauth/invoke")
    public String invoke(HttpServletRequest request){
        //2 用户同意授权  获取code
        String code= request.getParameter("code");

        //3 根据code 向腾讯服务器发送接口请求（认证服务器）
        String url="https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=" +MenuManager.appId+
                "&secret=" +MenuManager.appSecret+
                "&code=" +code+
                "&grant_type=authorization_code";
        JSONObject jsonObject= WeixinUtil.httpRequest(url,"GET",null);
        String access_token=jsonObject.getString("access_token");
        String openid=jsonObject.getString("openid");

        //根据openid查询wei_user 的主键id（wid）
        WeiUsers weiUsers = weiUsersService.selectWeiUsersByOpenid(openid);
        if(weiUsers == null){
            //如果weiUser表对应openid的数据
            log.info("---->该用户未收集个人信息:"+openid);
        }else {
            User user = userService.selectUserByWid(weiUsers.getId());
            if (user == null){
                //跳转微信登录页面
                request.setAttribute("wid",weiUsers.getId());
                return "weixin/user/login";
            }else {
                //跳转个人信息页面

                request.setAttribute("user",user);
                return "weixin/user/user_view";
            }
        }
        return "oauth";
    }


    // weixinMenu/meetingPubOauch
    @RequestMapping("meetingPubOauch")
    public void meetingPubOauch(HttpServletResponse response) throws IOException {
        //用户是否同意授权
        String path = MenuManager.REAL_URL + "weixinMenu/meetingPubOauch/invoke";
        try {
            path = URLEncoder.encode(path, "UTF-8");
            //https%3A%2F%2Fpassport.baidu.com%2Fphoenix%2Faccount%2Fafterauth%
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String url = "https://open.weixin.qq.com/connect/oauth2/authorize" +
                "?appid=" + MenuManager.appId +
                "&redirect_uri=" + path +
                "&response_type=code" +
                "&scope=snsapi_base" +
                "&state=java2005" +
                "#wechat_redirect";
        response.sendRedirect(url);

    }

    @RequestMapping("meetingPubOauch/invoke")
    public String invokeMeetingPub(HttpServletRequest request){

        //2 用户同意授权  获取code
        String code= request.getParameter("code");

        //3 根据code 向腾讯服务器发送接口请求（认证服务器）
        String url="https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=" +MenuManager.appId+
                "&secret=" +MenuManager.appSecret+
                "&code=" +code+
                "&grant_type=authorization_code";
        JSONObject jsonObject= WeixinUtil.httpRequest(url,"GET",null);
        String access_token=jsonObject.getString("access_token");
        String openid=jsonObject.getString("openid");

        //根据openid查询wei_user 的主键id（wid）
        WeiUsers weiUsers = weiUsersService.selectWeiUsersByOpenid(openid);
        if(weiUsers == null){
            //如果weiUser表对应openid的数据
            log.info("---->该用户未收集个人信息:"+openid);
        }else {
            User user = userService.selectUserByWid(weiUsers.getId());
            if (user == null){
                //跳转微信登录页面
                request.setAttribute("wid",weiUsers.getId());
                return "weixin/user/login";
            }else {

                //发单组的权限
                if (user.getRid()==1){
                    request.setAttribute("uid",user.getId());
                    return "weixin/meetingPub/meetingPub";
                }else {
                    return "weixin/unauth";
                }
            }
        }
        return "oauth";
    }




}
